package array.easy;

/**
 * 704. 二分查找
 *
 * @author wangtianqi
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] test = {-1, 0, 3, 5, 9, 12};
        System.out.println(binarySearchV1(test, 2));
    }

    /**
     * version 1.0
     * 显式的处理所有边界问题，便于理解与思考
     * @param nums
     * @param target
     * @return
     */
    public static int binarySearchV1(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int middle = ((right - left) / 2) + left;

            if (target > nums[right] || target < nums[left]) {
                return -1;
            }

            if (left == right) {
                return left;
            }

            if (target < nums[middle]) {
                right = middle - 1;
            } else if (target > nums[middle]) {
                left = middle + 1;
            } else if (target == nums[middle]) {
                return middle;
            }
        }
        return 0;
    }

    /**
     * 简化版
     * @param nums
     * @param target
     * @return
     */
    public static int binarySearchV2(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int middle = ((right - left) / 2) + left;

            if (target < nums[middle]) {
                right = middle - 1;
            } else if (target > nums[middle]) {
                left = middle + 1;
            } else if (target == nums[middle]) {
                return middle;
            }
        }
        return -1;
    }
}
